<template>
  <div class="wrap">
    <a-form ref="formRef" :model="formState" :rules="rules">
      <a-form-item label="报表编号" name="reportNumber">
        <a-input v-model:value="formState.reportNumber" placeholder="请输入报表编号" />
      </a-form-item>
      <a-form-item label="报表名称" name="reportName">
        <a-input v-model:value="formState.reportName" placeholder="请输入报表名称" />
      </a-form-item>
      <a-form-item label="报表类型" name="reportType">
        <a-radio-group v-model:value="formState.reportType">
          <a-radio :value="1">清单</a-radio>
          <a-radio :value="2">报表</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="报表频度" name="reportFrequency">
        <a-select v-model:value="formState.reportFrequency" placeholder="请选择">
          <a-select-option v-for="item in reportFrequencyList" :key="item" :value="item">{{
            item
          }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="制度日期" name="institutionDate">
        <a-input v-model:value="formState.institutionDate" placeholder="请输入制度日期" />
      </a-form-item>
      <a-form-item label="监管单位" name="regulationDept">
        <a-input v-model:value="formState.regulationDept" placeholder="请输入监管单位" />
      </a-form-item>
      <div class="dept-staff-wrap">
        <div style="width: 140px; text-align: right">
          <span style="color: #ff4d4f; font-size: 20px; vertical-align: middle">*</span>
          填报单位及人员：
        </div>
        <div class="dept-staff">
          <div class="dept-staff-labels">
            <div>填报部门：</div>
            <div>经办人：</div>
            <div>复核人：</div>
            <div>主管领导：</div>
          </div>
          <div v-for="(row, index) in formState.deptAndStaff" :key="index" class="dept-staff-items">
            <div class="dept-staff-item">
              <a-select v-model:value="row.dept" style="width: 120px" placeholder="选择部门">
                <a-select-option v-for="item in deptList" :key="item" :value="item">{{
                  item
                }}</a-select-option>
              </a-select>
            </div>
            <div class="dept-staff-item">
              <a-input-search
                v-model:value="row.operator"
                placeholder="搜索经办人"
                @click="selectStaff(index, 'operator')"
              />
              <div style="width: 25px"></div>
            </div>
            <div class="dept-staff-item">
              <a-input-search
                v-model:value="row.reviewer"
                placeholder="搜索复核人"
                @click="selectStaff(index, 'reviewer')"
              />
              <div style="width: 25px"></div>
            </div>
            <div class="dept-staff-item">
              <a-input-search
                v-model:value="row.manager"
                placeholder="搜索主管/领导"
                @click="selectStaff(index, 'manager')"
              />
              <CloseCircleOutlined
                style="color: #c50000; width: 20px; margin-left: 5px"
                @click="deleteDeptAndStaff(index)"
              ></CloseCircleOutlined>
            </div>
          </div>
        </div>
      </div>
      <a-form-item style="margin-top: 10px; margin-left: 140px">
        <a-button
          style="background-color: #c50000; color: white; border-radius: 5px"
          @click="addDeptAndStaff"
        >
          添加单位及人员
          <template #icon>
            <PlusOutlined />
          </template>
        </a-button>
      </a-form-item>
      <a-form-item style="margin-left: 140px">
        <custom-upload
          v-model:dir-id="formState.dirId"
          action="/statement/dirmanagement/uploadTemplate"
        ></custom-upload>
      </a-form-item>
      <a-form-item style="margin-left: 140px">
        <a-button style="color: white; background-color: #f50" @click="submit">提交</a-button>
        <a-button style="margin-left: 10px; background-color: #ececec" @click="cancel"
          >取消</a-button
        >
      </a-form-item>
    </a-form>

    <select-staff
      title="选择人员"
      :modal-visible="showSelectStaff"
      @select-staff="handleSelectStaff"
    ></select-staff>
  </div>
</template>

<script lang="ts">
  import { defineComponent, ref, reactive, toRefs, UnwrapRef, toRaw, watch } from 'vue'
  import { Button, Form, Input, Select, Radio } from 'ant-design-vue'
  import { PlusOutlined, CloseCircleOutlined } from '@ant-design/icons-vue'
  import { ValidateErrorEntity } from 'ant-design-vue/es/form/interface'
  import CustomUpload from '@/components/CustomUpload.vue'
  import emitter, { EventsEnum } from '@/utils/emitter'
  import { useRoute } from 'vue-router'
  import SelectStaff from '@/views/report/directory/SelectStaff.vue'
  import { useDirectoryStore } from '@/store/modules/directory'
  import { convertReportFrequencyChinese2Code } from '@/views/data'
  //   import { queryDeptList, DeptUserList } from '@/api/directory'

  interface FormState {
    reportNumber: string
    reportName: string
    deptAndStaff: DeptAndStaff[]
    reportType: number
    reportFrequency: string | undefined
    institutionDate: string
    regulationDept: string
    dirId: string
  }
  interface DeptAndStaff {
    dept: string | undefined // 填报部门
    operator: string // 经办人
    reviewer: string // 复核人
    manager: string // 主管领导
  }
  export default defineComponent({
    name: 'AddDirectory',
    components: {
      SelectStaff,
      CustomUpload,
      PlusOutlined,
      CloseCircleOutlined,
      [Button.name]: Button,
      [Form.name]: Form,
      [Form.Item.name]: Form.Item,
      [Input.name]: Input,
      [Input.Search.name]: Input.Search,
      [Select.name]: Select,
      ASelectOption: Select.Option,
      'a-radio-group': Radio.Group,
      [Radio.name]: Radio
    },
    props: {
      title: {
        type: String,
        default: ''
      },
      fields: {
        type: Object,
        default: () => ({})
      }
    },
    setup() {
      const formRef = ref()
      const route = useRoute()
      const { query } = route
      // console.log(query)

      const formState: UnwrapRef<FormState> = reactive({
        reportNumber: (query.reportNumber as string) || '',
        reportName: (query.reportName as string) || '',
        reportType: 1,
        institutionDate: (query.institutionDate as string) || '',
        deptAndStaff: [
          {
            dept: undefined,
            operator: '',
            reviewer: '',
            manager: ''
          }
        ],
        regulationDept: (query.regulationDept as string) || '',
        reportFrequency: (query.regulationDept as string) || undefined,
        dirId: ''
      })

      const state = reactive({
        reportFrequencyList: ['日报', '周报', '月报', '年报', '半月报'],
        deptList: ['人事部', '财务部', '市场部'],
        showSelectStaff: false,
        selectedStaffItem: {
          index: 0, // 选中的item在表单formState.deptAndStaff中的位置（选择部门和人员的行号）
          property: '' // 选中的item在表单formState.deptAndStaff中所在位置的属性
        }
      })

      const rules = {
        regulationDept: [{ required: true, message: '请输入监管单位', trigger: 'blur' }],
        reportNumber: [{ required: true, message: '请输入报表编号', trigger: 'blur' }],
        reportName: [{ required: true, message: '请输入报表名称', trigger: 'blur' }],
        reportType: [
          { required: true, message: '请选择报表类型', trigger: 'change', type: 'number' }
        ]
      }
      useDirectoryStore()
        .queryDeptList()
        .then((res) => {
          console.log(res)
        })
      useDirectoryStore().DeptUserList()

      // 初始化表单数据
      const initialFormState = Object.assign({}, toRaw(formState))
      // 表单重置
      const reset = () => {
        Object.assign(formState, initialFormState)
      }

      console.log(query)

      // const arr = []
      // for (const item of formState.deptAndStaff) {
      //   const obj = {
      //     dirOrgName=item.dept
      //     dirUserName=item.operator
      //   }
      //   arr.push(obj)
      // }

      // 点击提交按钮
      const submit = () => {
        formRef.value
          .validate()
          .then(() => {
            // console.log(query.title)
            // console.log('11')
            if (query?.title === '修改目录') {
              useDirectoryStore()
                .updateManagementRequest({
                  dirFrequentness: convertReportFrequencyChinese2Code(formState.reportFrequency),
                  dirId: query.dirId as string,
                  dirName: formState.reportName,
                  dirNumber: formState.reportNumber,
                  dirSuperviseorg: formState.regulationDept,
                  dirType: formState.reportType.toString(),
                  dirFillins: [
                    {
                      dirOrgId: '1',
                      dirOrgName: '1',
                      dirUserId: '1',
                      dirUserName: '1',
                      dirUserRole: 0
                    }
                  ]
                })
                .then(() => {
                  console.log('修改完成')
                  console.log(query.dirId)
                  console.log(query)

                  reset()
                })
            } else {
              useDirectoryStore()
                .addManagementFile({
                  dirFrequentness: convertReportFrequencyChinese2Code(formState.reportFrequency),
                  dirName: formState.reportName,
                  dirNumber: formState.reportNumber,
                  dirId: formState.dirId,
                  dirRegimeDate: formState.institutionDate,
                  dirSuperviseorg: formState.regulationDept,
                  dirType: formState.reportType.toString(),
                  dirFillins: [
                    {
                      dirOrgId: '1',
                      dirOrgName: '1',
                      dirUserId: '1',
                      dirUserName: '1',
                      dirUserRole: 0
                    }
                  ]
                })
                .then(() => {
                  reset()
                })
            }
          })
          .catch((error: ValidateErrorEntity<FormState>) => {
            console.log('error', error)
          })
      }

      const cancel = () => {
        emitter.emit(EventsEnum.CLOSE_TAB, route)
      }

      const addDeptAndStaff = () => {
        formState.deptAndStaff.push({
          dept: undefined,
          operator: '',
          reviewer: '',
          manager: ''
        })
      }

      const deleteDeptAndStaff = (index) => {
        if (formState.deptAndStaff.length > 1) {
          formState.deptAndStaff.splice(index, 1)
        }
      }

      const showSelectStaff = () => {
        state.showSelectStaff = false
        setTimeout(() => {
          state.showSelectStaff = true
        }, 0)
      }

      const selectStaff = (index, property) => {
        showSelectStaff()
        state.selectedStaffItem = {
          index: index,
          property: property
        }
      }

      const handleSelectStaff = (data) => {
        formState.deptAndStaff[state.selectedStaffItem.index][state.selectedStaffItem.property] =
          data
      }

      return {
        ...toRefs(state),
        formState,
        rules,
        formRef,
        submit,
        selectStaff,
        handleSelectStaff,
        addDeptAndStaff,
        deleteDeptAndStaff,
        cancel
      }
    }
  })
</script>

<style lang="scss" scoped>
  .wrap {
    display: flex;
    justify-content: center;
    margin-left: -70px;
  }
  .form-wrap {
  }
  .item-wrap {
  }
  .dept-staff-wrap {
    display: flex;
    flex-direction: row;
    .dept-staff {
      display: flex;
      flex-direction: column;
      .dept-staff-labels {
        display: flex;
        flex-direction: row;
        & > div {
          flex: 1;
          width: 140px;
        }
      }
      .dept-staff-items {
        display: flex;
        flex-direction: row;
        align-items: center;
        margin: 5px 0;
        .dept-staff-item {
          flex: 1;
          display: flex;
          flex-direction: row;
          align-items: center;
          width: 120px;
        }
      }
    }
  }
  ::v-deep(.ant-form-item-label) {
    & > label {
      display: flex;
      width: 140px;
      justify-content: flex-end;
    }
  }
</style>
